<?php
/**
 * Yotaku shop - yshop
 * Copyright (c) 2016 http://www.yotaku.cn All rights reserved.
 * Author: Creatint <creatint@163.com> <http://creatint.yotaku.cn>
 */
namespace Admin\Model;
use Think\Model;

class CategoryModel extends Model{
    //自动验证
    protected $_validate = array(
        array('sort','number','排序数据错误'),
    );
    protected $error    =   '';
    public function getCategory(){
        $map    =   array();
        $result =   $this->where($map)->select();
        if(!is_array($result)){
            $this->error    =   '获取失败';
            return false;
        }
//        $sql    =   'SELECT a.id,a.title,a.pid FROM y_category a LEFT JOIN y_category b ON a.pid=b.id GROUP BY a.pid';
//        $result =   $this->query($sql);
        //$result =   children($result);
        
        return $result;
    }
    public function getTree($id = 0, $field = true){
        //获取所有分类
        $map    =   array();
        $list   =   $this->field($field)->where($map)->order('sort')->select();
        $list   =   list_to_tree($list,$pk = 'id', $pid = 'pid', $child = 'child', $root = $id);
        return $list;
    }
    public function getDetail($id){
        if(!$id){
            $this->error = '分类ID为空';
            return false;
        }
        $map = array();
        $map['id']  =   $id;
        $res = $this->where($map)->find();
        if(!$res){
            $this->error = '分类数据为空';
            return false;
        }
        return $res;
    }
    public function update($data=null){
        /* 获取数据对象 */
        $data = $this->create($data);
        if(empty($data)){
            $this->error    =   '分类数据为空';
            return false;
        }
        if(empty($data['id'])){ //新增
            $id =   $this->add();
            if(!$id){
                $this->error = '新增分类出错';
                return false;
            }
            $data = array_merge(array('id'=>$id),$data);
        }else{
            $status = $this->save();
            if(false === $status){
                $this->error = '更新分类出错';
                return false;
            }
        }
        return $data;

    }
    public function getError(){
        return $this->error;
    }
    public function del($id){
        if(empty($id)){
            $this->error = '请选择要删除的分类';
        }
        $map = array('id'=>array('IN',trim(implode(',',$id),',')));
        if($this->where($map)->delete()){
            return true;
        }else{
            $this->error = '无此条数据';
            return false;
        }
    }
}